import { Component, Input, OnInit, AfterViewInit } from '@angular/core';
import { TreeNode } from 'primeng/primeng';
import { QkPartService } from './qkpart.service';
@Component({
  selector: 'qkunit-selector',
  templateUrl: './qkunit-selector.component.html',
  styleUrls: ['./qkunit-selector.component.scss'],
  providers: [QkPartService]
})
export class QkUnitSelectorComponent implements OnInit {
  @Input() checkedParts: TreeNode[];
  checkedUnits: TreeNode[] = [];
  units: TreeNode[] = []; //机构树
  loading: boolean = true;
  suggestion: any;
  suggestions: TreeNode[]; //下拉选项

  constructor(private qkPartService: QkPartService) { }

  ngOnInit() {
    this.qkPartService.getUnitTree(0, true)
      .subscribe(data => {
        this.loading = false;
        this.units = data;
        // this.checkedParts.forEach(node => {
        //   if (node['data']['type'] == '机构') {
        //     this.recursionExpendSuggestionTreeNode(this.units, node['data']['unitCode']);
        //   }
        // });
      });
  }

  /**人员查找 */
  search(event) {
    if (!event.query) return;
    this.qkPartService.searchUnitByName(event.query).subscribe(data => {
      data.forEach(ele => ele["unitName"] = ele["unitName"] + "(" + ele["unitId"] + ")")
      this.suggestions = data;
    });
  }

  /** 树节点展开事件 */
  unitNodeExpand(event) {
    if (event.node && event.node.children.length == 0) {
      this.qkPartService.getUnitTree(event.node.id, false).subscribe(nodes => event.node.children = nodes);
    }
  }

  /**选择下拉事件 */
  selectSuggestion() {
    this.recursionExpendSuggestionTreeNode(this.units, this.suggestion.unitCode);
  }

  /**递归展开查询的树 */
  recursionExpendSuggestionTreeNode(units: TreeNode[], unitCode: string) {
    units.forEach(ele => {
      if (unitCode.indexOf('/' + ele['id'] + '/') != -1) {
        if (unitCode == ele.data['code']) {
          this.checkedUnits.push(ele);
          return
        }
        //展开树节点
        ele.expanded = true;
        if (ele.children.length > 0) {
          this.recursionExpendSuggestionTreeNode(ele.children, unitCode);
        } else {
          this.qkPartService.getUnitTree(+ele['id'], false, "false").subscribe(nodes => {
            ele.children = nodes;
            this.recursionExpendSuggestionTreeNode(ele.children, unitCode);
          });
        }
      } else {
        //关闭非节点
        ele.expanded = false;
      }
    })
  }
}
